import subprocess
from os.path import dirname, abspath
import time


# 捕获系统异常
def system_exe_output(cmd):
    assert(type(cmd) == str)
    status, result = subprocess.getstatusoutput(cmd)
    if int(status) != 0:
        raise Exception(result)
    return result


# 把本地文件推送到远端服务器（需要ssh）
def push_file(src_path, dest_user, dest_host, dest_path=None, is_cover=True):
    cmd_conf = '-avzp'
    if not is_cover:
        cmd_conf += 'u'
    if dest_path is None:
        root_path = dirname(dirname(dirname(dirname(abspath(__file__)))))
        # dest_root_path = '/cloud/data/lirui/projects'
        dest_root_path = '/data/bigdata'
        dest_path = dirname(dest_root_path + src_path.replace(root_path, ''))
    print("推送到的目录是：%s" % dest_path)
    result = system_exe_output("rsync %s --progress %s %s@%s:%s" % (cmd_conf, src_path, dest_user, dest_host, dest_path))
    print(result)

if __name__ == '__main__':
    # 本地路径
    local_path = dirname(dirname(abspath(__file__)))
    # 远端配置
    hosts = ['10.152.43.222', '10.152.119.165']
    users = ['root', 'root']
    paths = ['/home/lirui/projects/', '/home/lirui/projects/']
    for j in range(len(hosts)):
        # 重试3次
        for i in range(3):
            try:
                push_file(local_path, users[j], hosts[j], paths[j])
                break
            except:
                time.sleep(1)
